/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package luft27.zorcon.input;

import luft27.propertytree.PropertyNode;
import net.java.games.input.Component;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;

/**
 *
 * @author amalikov
 */
class Control {
	public static boolean TRIGGER = true;
	
	public Control(PropertyNode node) {
		this(node, false);
	}
	
	public Control(PropertyNode node, boolean trigger) {
		controller = getControllerByName(node.get("/controller").asString());
		component = getComponentIdentifierByName(controller, node.get("/component").asString());
		inverted = node.get("/inverted").asBool();
		this.trigger = trigger;
		this.lastValue = 0;
	}

	public float getValue() {
		if (controller == null || component == null)
			return 0;
		controller.poll();
		float value = controller.getComponent(component).getPollData() * (inverted ? -1 : 1);
		float triggerValue = value == lastValue ? 0 : value;
		lastValue = value;
		return trigger ? triggerValue : value;
	}

	private Controller getControllerByName(String name) {
		if (name == null)
			return null;
		final Controller[] ca = ControllerEnvironment.getDefaultEnvironment().getControllers();
		for (Controller c : ca)
			if (c.getName().equals(name))
				return c;
		return null;
	}

	private Component.Identifier getComponentIdentifierByName(Controller controller, String name) {
		if (controller == null || name == null)
			return null;
		final Component[] ca = controller.getComponents();
		for (Component c : ca)
			if (c.getIdentifier().getName().equals(name))
				return c.getIdentifier();
		return null;
	}
	
	private final Controller controller;
	private final Component.Identifier component;
	private final boolean inverted;
	private final boolean trigger;
	private float lastValue;
}
